package com.cmccgz.udacs_landlord_webapp.main.unlock;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.cmccgz.baselibrary.base.BaseFragment;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.adapter.LeDeviceListAdapter;
import com.cmccgz.udacs_landlord_webapp.base.AppConfig;
import com.cmccgz.udacs_landlord_webapp.bean.DeviceInfoBean;
import com.cmccgz.udacs_landlord_webapp.utils.ViewHelper;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import static android.content.Context.BIND_AUTO_CREATE;
import static com.cmccgz.udacs_landlord_webapp.R.id.rv_list;

/**
 * @author: Huang
 * @Descripion:
 * @date 2017/7/5 16:49
 */

public class BtUnlockFragment extends BaseFragment implements BtUnlockContract.View, View.OnClickListener {

    private LeDeviceListAdapter mLeDeviceListAdapter;
    private static final int REQUEST_ENABLE_BT = 1;
    private List<DeviceInfoBean> deviceList;

    private BluetoothStatusReceiver mBlueStateReceiver = new BluetoothStatusReceiver();
    private BtUnlockContract.Presenter presenter;

    private BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
//                BluetoothDevice device = intent.getParcelableExtra("device");
//                mLeDeviceListAdapter.addDevice(device);
//                presenter.deviceConnect(device);
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
//                BluetoothDevice device = intent.getParcelableExtra("device");
                presenter.deviceDisConnect();
                dismissUnlockDialog("设备连接已断开！");
            } else if (BluetoothLeService.ACTION_GATT_DESCRIPTOR_WRITE_SUCCESS.equals(action)) {
                Logger.e("收到descriptor写入成功广播");
//                BluetoothDevice device = intent.getParcelableExtra("device");
                presenter.deviceConnect();
            } else if (BluetoothLeService.ACTION_GATT_DESCRIPTOR_WRITE_FAILED.equals(action)) {
//                BluetoothDevice device = intent.getParcelableExtra("device");
                presenter.deviceDisConnect();
                dismissUnlockDialog("descriptor写入失败！");
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED_FAILED.equals(action)) {
//                BluetoothDevice device = intent.getParcelableExtra("device");
                presenter.deviceDisConnect();
                dismissUnlockDialog("服务发现失败！");
            } else if (BluetoothLeService.ACTION_GATT_CHARACTERISTIC_WRITE_FAILED.equals(action)) {
//                BluetoothDevice device = intent.getParcelableExtra("device");
                presenter.deviceDisConnect();
                dismissUnlockDialog("数据写入失败！");
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                presenter.displayData(intent);
            } else if (BluetoothLeService.ACTION_STATE_ON.equals(action)) {
                showToast("蓝牙已打开");
                presenter.bluetoothEnable();
            } else if (BluetoothLeService.ACTION_STATE_OFF.equals(action)) {
                showToast("蓝牙已关闭");
                presenter.unbindService();
            }
        }
    };
    private boolean isBound = false;
    private DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            presenter.scanDevice(false);
        }
    };
    private TextView tv_enable;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_btunlock;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        mContext.registerReceiver(mBlueStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
        presenter.start();
    }

    private IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED_FAILED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DESCRIPTOR_WRITE_SUCCESS);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DESCRIPTOR_WRITE_FAILED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CHARACTERISTIC_WRITE_FAILED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothLeService.ACTION_STATE_ON);
        intentFilter.addAction(BluetoothLeService.ACTION_STATE_OFF);
        return intentFilter;
    }

    @Override
    protected void initView() {
        ViewHelper mViewHelper = ViewHelper.instance(this);
        if (mViewHelper != null) {
            mViewHelper.setTitle("蓝牙开门");
            mViewHelper.setImageRight(R.mipmap.titlebar_search);
            mViewHelper.setImageRightVisable(true);
            mViewHelper.setBackTextVisable(true);
        }

        initData();

        RecyclerView lv_device = (RecyclerView) findViewById(rv_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        lv_device.setLayoutManager(layoutManager);
        lv_device.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));
        mLeDeviceListAdapter = new LeDeviceListAdapter(mContext, presenter, deviceList);
        lv_device.setAdapter(mLeDeviceListAdapter);

        tv_enable = (TextView) findViewById(R.id.tv_enable);
        tv_enable.setVisibility(isBound ? View.GONE : View.VISIBLE);

    }

    private void initData() {

        List<DeviceInfoBean> list = AppConfig.getDeviceList();
        this.deviceList = new ArrayList<>();
        for (DeviceInfoBean device : list) {
            this.deviceList.add(device);
        }
    }

    @Override
    public BluetoothAdapter checkBlueTooth() {
        if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(mContext, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
            mContext.finish();
        }
        final BluetoothManager bluetoothManager =
                (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(mContext, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            mContext.finish();
        } else if (!mBluetoothAdapter.isEnabled()) {
            Logger.e("初始化蓝牙");
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQUEST_ENABLE_BT);
        } else {
            presenter.bluetoothEnable();
        }
        return mBluetoothAdapter;
    }

    @Override
    public void bindService(ServiceConnection connection) {
        Intent gattServiceIntent = new Intent(mContext, BluetoothLeService.class);
        isBound = mContext.bindService(gattServiceIntent, connection, BIND_AUTO_CREATE);
        if (tv_enable != null) {
            tv_enable.setVisibility(isBound ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public void unbindService(ServiceConnection connection) {
        if (isBound && connection != null) {
            mContext.unbindService(connection);
            isBound = false;
        }
        if (tv_enable != null) {
            tv_enable.setVisibility(isBound ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public void dismissWaitingDialog() {
        dismissLoadingDialog();
    }

    @Override
    public void showWaitingDialog() {
        showLoadingDialog("正在搜索设备...", cancelListener);
    }

    @Override
    public void showUnlockDialog() {
        dismissLoadingDialog();
        showLoadingDialog("正在解锁，请稍候...");
    }

    @Override
    public void dismissUnlockDialog(String msg) {
        dismissLoadingDialog(msg);
    }

    @Override
    public void addDevice(BluetoothDevice device) {
        if (mLeDeviceListAdapter != null) {
            mLeDeviceListAdapter.addDevice(device);
        }
    }

    @Override
    public void setPresenter(BtUnlockContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // User chose not to enable Bluetooth.
        if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
            showToast("请开启蓝牙！");
            mContext.finish();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back:
                mContext.onBackPressed();
                break;
            case R.id.iv_right:
                mLeDeviceListAdapter.clear();
                presenter.scanDevice(true);
                break;
        }
    }


    public static BtUnlockFragment newInstance() {
        return new BtUnlockFragment();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        presenter.unbindService();
        mContext.unregisterReceiver(mBlueStateReceiver);
        mContext.unregisterReceiver(mGattUpdateReceiver);
    }
}
